package com.moku.tester;

import java.util.Timer;

import net.rim.device.api.ui.MenuItem;
import net.rim.device.api.ui.UiApplication;
import net.rim.device.api.ui.component.LabelField;
import net.rim.device.api.ui.component.Menu;
import net.rim.device.api.ui.component.RichTextField;
import net.rim.device.api.ui.container.MainScreen;

public class HttpTesterScreen extends MainScreen {

	private RichTextField richTextField;
	private LabelField titleLabelField;

	private Timer timer = null;
	private TestTask testTask = null;
	private TestOptionsScreen testOptionsScreen;

	private MenuItem _testOptionMenu = new MenuItem("Options", 110, 10) {
		public void run() {
			testOptionsScreen.display();
		}
	};

	private MenuItem _startMenu = new MenuItem("Start Test", 110, 10) {
		public void run() {
			if (timer != null) {
				return;
			} else {
				timer = new Timer();
				if (testTask == null) {
					testTask = new TestTask(testOptionsScreen);
				}
				timer.scheduleAtFixedRate(testTask, 1000, testOptionsScreen
						.getInterval());
				titleLabelField.setText("Tester - [running]");
			}
		}
	};
	private MenuItem _stopMenu = new MenuItem("Stop Test", 110, 10) {
		public void run() {
			if (testTask != null) {
				testTask.stop();
				testTask = null;
			}
			if (timer != null) {
				timer.cancel();
				timer = null;
			}
			titleLabelField.setText("Tester - [stopped]");
		}
	};
	private MenuItem _exitMenu = new MenuItem("Exit", 110, 10) {
		public void run() {
			exit();
		}
	};

	public void close() {
		UiApplication.getUiApplication().requestBackground();
	}

	public RichTextField getRichTextField() {
		return richTextField;
	}

	void exit() {
		if (testTask != null) {
			testTask.disableAlarm();
		}
		System.exit(0);
	}

	protected void makeMenu(Menu menu, int instance) {
		menu.add(_startMenu);
		menu.add(_stopMenu);
		menu.add(_testOptionMenu);
		menu.addSeparator();
		menu.add(_exitMenu);
	}

	HttpTesterScreen() {
		testOptionsScreen = new TestOptionsScreen();
		titleLabelField = new LabelField("Tester - [stopped]",
				LabelField.ELLIPSIS | LabelField.USE_ALL_WIDTH);
		setTitle(titleLabelField);
		richTextField = new RichTextField();
		add(richTextField);

	}
}
